package api

import (
	"gitee.com/yangwencheng/vblog/apps/user"
	"gitee.com/yangwencheng/vblog/common"
	"github.com/gin-gonic/gin"
)

func (h *Handler) QueryUser(ctx *gin.Context) {
	// 请求对象
	qbr := user.NewQueryUserRequest()

	if err := ctx.ShouldBindQuery(qbr); err != nil {
		common.SendFail(ctx, err)
		return
	}
	userSet, err := h.srv.QueryUser(ctx, qbr)

	if err != nil {
		common.SendFail(ctx, err)
		return
	}
	common.SendSuccess(ctx, common.NewResult(userSet))
}

func (h *Handler) CreateUser(ctx *gin.Context) {

	cbr := user.NewCreateUserRequest()
	ctx.BindJSON(cbr)
	user, err := h.srv.CreateUser(ctx, cbr)
	if err != nil {
		common.SendFail(ctx, err)
		return
	}
	common.SendSuccess(ctx, common.NewResult(user))

}

func (h *Handler) ShowUser(ctx *gin.Context) {
	sbr := &user.ShowUserRequest{}
	ctx.BindUri(sbr)
	user, err := h.srv.ShowUser(ctx, sbr)

	if err != nil {
		common.SendFail(ctx, err)
		return
	}
	common.SendSuccess(ctx, common.NewResult(user))
}

func (h *Handler) UpdateUser(ctx *gin.Context) {
	cbr := user.NewCreateUserRequest()
	ctx.BindJSON(cbr)
	user := user.NewUser()
	ctx.BindUri(user)

	user, err := h.srv.UpdateUser(ctx, cbr, user)
	if err != nil {
		common.SendFail(ctx, err)
		return
	}
	common.SendSuccess(ctx, common.NewResult(user))
}

func (h *Handler) DeleteUser(ctx *gin.Context) {
	dbr := &user.DeleteUserRequest{}
	ctx.BindUri(dbr)
	user, err := h.srv.DeleteUser(ctx, dbr)

	if err != nil {
		common.SendFail(ctx, err)
		return
	}
	common.SendSuccess(ctx, common.NewResult(user))
}

func (h *Handler) Login(ctx *gin.Context) {
	in := user.NewLoginUserRequest()
	ctx.BindJSON(in)
	user, err := h.srv.Login(ctx, in)

	if err != nil {
		common.SendFail(ctx, err)
		return
	}
	common.SendSuccess(ctx, common.NewResult(user))
}

func (h *Handler) Info(ctx *gin.Context) {
	userInfo := user.NewUserInfo()
	userInfo.Name = ctx.GetString("user_name")
	userInfo.ID = ctx.GetInt("user_id")
	common.SendSuccess(ctx, common.NewResult(userInfo))
}
